#include <napi.h>
#include "SpoutSender.h"

SpoutSender mySender;

Napi::Buffer<HGLRC> CreateRC(const Napi::CallbackInfo &info)
{
  Napi::Env env = info.Env();
  std::cout << "info[0]: " << info[0] << endl;
  std::cout << "info[0].As<Napi::Buffer<HWND>>(): " << info[0].As<Napi::Buffer<HWND>>() << endl;

  HWND hwnd = *info[0].As<Napi::Buffer<HWND>>().Data();
  std::cout << "hwnd: " << hwnd << endl;

  HDC hdc = GetDC(hwnd);
  std::cout << "hdc: " << hdc << endl;

  //初始化像素格式
  static PIXELFORMATDESCRIPTOR pfd =
      {
          sizeof(PIXELFORMATDESCRIPTOR), //上述格式描述符的大小
          1,                             //版本号
          PFD_DRAW_TO_WINDOW |           //格式支持窗口
              PFD_SUPPORT_OPENGL |       //格式必须支持OpenGL
              PFD_DOUBLEBUFFER,          //必须支持双缓冲
          PFD_TYPE_RGBA,                 //申请RGBA 格式
          24,                            //选定色彩深度
          0, 0, 0, 0, 0, 0, 0, 0,        //忽略RGBA
          0,                             //无累加缓存
          0, 0, 0, 0,                    //忽略聚集位
          32,                            //32位Z-缓存(深度缓存)
          0,                             //无蒙板缓存
          0,                             //无辅助缓存
          PFD_MAIN_PLANE,                //主绘图层
          0,                             //Reserved
          0, 0, 0                        //忽略层遮罩
      };

  //选择一个最适合pfd描述的像素格式索引值
  int nPixelFormat = ChoosePixelFormat(hdc, &pfd);

  //为DC设置像素格式
  SetPixelFormat(hdc, nPixelFormat, &pfd);

  // create a rendering context
  HGLRC hglrc = wglCreateContext(hdc);
  std::cout << "hglrc: " << hglrc << endl;
  std::cout << "GetLastError: " << GetLastError() << endl;

  // make it the calling thread's current rendering context
  bool MakeCurrent = wglMakeCurrent(hdc, hglrc);
  std::cout << "MakeCurrent: " << MakeCurrent << endl;

  return Napi::Buffer<HGLRC>::New(env, &hglrc, 10);
}

Napi::Boolean CreateSender(const Napi::CallbackInfo &info)
{
  Napi::Env env = info.Env();

  const char *SenderName = info[0].As<Napi::String>().Utf8Value().c_str();
  unsigned int Width = info[1].As<Napi::Number>().Uint32Value();
  unsigned int Height = info[1].As<Napi::Number>().Uint32Value();
  bool result = mySender.CreateSender(SenderName, Width, Height);

  return Napi::Boolean::New(env, result);
}

Napi::Object Init(Napi::Env env, Napi::Object exports)
{
  exports.Set(Napi::String::New(env, "CreateRC"),
              Napi::Function::New(env, CreateRC));
  exports.Set(Napi::String::New(env, "CreateSender"),
              Napi::Function::New(env, CreateSender));
  return exports;
}

NODE_API_MODULE(spout, Init)
